/*
 * SendProblemBehaviour.java
 *
 * Created on 5 de Fevereiro de 2008, 18:51
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package br.ufal.ic.mediator.behaviours;

import jade.*;
import jade.core.AID;
import jade.core.behaviours.OneShotBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.domain.FIPAException;
import jade.lang.acl.ACLMessage;

/**
 *
 * @author Raphael
 */
public class SendProblemBehaviour extends OneShotBehaviour {
    private String problem;
    
    /**
     * Creates a new instance of SendProblemBehaviour
     */
    public SendProblemBehaviour(String problem) {
        this.problem = problem;
    }

    public void action() {        
        AID[] aidTutor = search(this.problem);
        ACLMessage message = new ACLMessage(ACLMessage.INFORM);
        message.setContent(this.problem);
        message.addReceiver(aidTutor[0]);
        myAgent.send(message);                
    }
    
    private AID[] search(String service) {
        ServiceDescription serviceDescription = new ServiceDescription();
        serviceDescription.setName(service);
        
        DFAgentDescription agentDescription = new DFAgentDescription();
        agentDescription.addServices(serviceDescription);

        try {
            DFAgentDescription results[] = DFService.search(myAgent, agentDescription);
            AID[] aid = new AID[results.length];

            for (int i=0; i<results.length; i++) {
                aid[i] = results[i].getName();
            }

            return aid;
        } catch (FIPAException ex) {
            return null;
        }
    }            
}
